package sk.tuke.android4all.typeactivity;

import sk.tuke.android4all.services.Tts;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class TypeActivity extends Activity {

	private static String TAG = "TypeActivity";
	
	private String mTextIn = null;
	private Tts mSpeechEngine = null;
	private String caller = "";
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_type);
		
		mSpeechEngine = new Tts(getBaseContext());
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
		    mTextIn = extras.getString("text");
		    caller = extras.getString("caller");
		}
		if(mTextIn == null){
			mTextIn = "";
		}
		
		mSpeechEngine.sayMessage(mTextIn);
		
		final EditText mEdit = (EditText) findViewById(R.id.textedit);
		mEdit.requestFocus();
		mEdit.setOnEditorActionListener(new OnEditorActionListener(){

			@Override
			public boolean onEditorAction(TextView rootView, int actionId, KeyEvent actionEvent) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH ||
			            actionId == EditorInfo.IME_ACTION_DONE ||
			            actionEvent.getAction() == KeyEvent.ACTION_DOWN &&
			            actionEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
			           		Log.i(TAG, "Typing ended");
			           		String returnedText = mEdit.getText().toString();
			           		mSpeechEngine.sayMessage(getResources().getString(R.string.ended) + " " + returnedText);
			           		try {
								while(!mSpeechEngine.isSpeechCompleted()){
									Thread.sleep(500);
								}
							} catch (InterruptedException e) {
								//Do nothing
							}
			           		Intent resultIntent = new Intent();
			           		resultIntent.putExtra("text", returnedText);
			           		resultIntent.putExtra("caller", caller);
			           		setResult(Activity.RESULT_OK, resultIntent);
			           		mSpeechEngine.dispose();
			           		finish();
			           		return true;            
			    }
			    return false;
			}});
	}
}
